package com.lagou;

import com.lagou.request.RpcRequest;
import com.lagou.serialize.JSONSerializer;
import com.lagou.serialize.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class RpcEncoder extends MessageToByteEncoder {

    private Class<?> clazz;

    private Serializer serializer;

    public RpcEncoder(){
        this.clazz = RpcRequest.class;
        this.serializer = new JSONSerializer();
    }

//    public RpcEncoder(Class<?> clazz){
//        new RpcEncoder(clazz,null);
//    }
    public RpcEncoder(Class<?> clazz,Serializer serializer){
        this.clazz = clazz;
        if(serializer == null)
            this.serializer = new JSONSerializer();
        else
            this.serializer = serializer;
    }

    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        if(clazz != null && clazz.isInstance(o)){
            byte[]  bytes = serializer.serialize(o);
            byteBuf.writeInt(bytes.length);
            byteBuf.writeBytes(bytes);
        }
    }
}
